import bowlImg from '../../assets/port.jpg'
import dice1 from '../../assets/1.jpg'
import dice2 from '../../assets/2.jpg'
import dice3 from '../../assets/3.jpg'
import dice4 from '../../assets/4.jpg'
import dice5 from '../../assets/5.jpg'
import dice6 from '../../assets/6.jpg'
import utils from '../../utils'
import Lamp from '@/components/Lamp'
import MyAudio from '@/components/MyAudio'
import MobileDetect from 'mobile-detect'
import bobingService from '@/api/bobing-api.js'
import { getUser, setUser } from '@/utils/auth'
import {
  Dialog,
  Button,
  NoticeBar,
  Popup,
  Cell,
  CellGroup,
  Field,
  Toast
} from 'vant'

export default {
  name: 'Home',
  components: {
    Lamp,
    MyAudio,
    [Dialog.name]: Dialog,
    [Button.name]: Button,
    [NoticeBar.name]: NoticeBar,
    [Popup.name]: Popup,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Toast.name]: Toast,
    [Field.name]: Field,
  },
  data() {
    return {
      bowlImg,
      soundUrl: '../../static/saizi.mp3',//需要配置成url链接
      soundEndUrl: '',
      rptIsShow: false,
      startDisabled: false,
      showPopup: true,
      clickimes: 0,
      showPassword: false,
      currentSerialNO: 0,
      password: '',
      times:0,
      currentUser: {
        userName: '',
        times:0,
        authorizationCode:''
      },
      lampUserName:'尊敬的贵宾',
      noticeMessage: '👏👏👏祝大家玩的开心，博出好运气...🎉🎉🎉🎉🎉🎉',
      rptList: [
        dice1,
        dice2,
        dice3,
        dice4,
        dice5,
        dice6
      ],
      ranRptList: [],
      mzUrl:'../../static//audio1.mp3',//需要配置成url链接
      yxUrl:'../../static//audio2.mp3',//需要配置成url链接
      ejUrl:'../../static//audio3.mp3',//需要配置成url链接
      sjUrl:'../../static//audio4.mp3',//需要配置成url链接
      shUrl:'../../static//audio5.mp3',//需要配置成url链接
      dtUrl:'../../static//audio6.mp3',//需要配置成url链接
      zyUrl:'../../static//audio7.mp3',//需要配置成url链接
    }
  },
  methods: {
    startBobing() {
      let _this = this
      let _user = getUser();
      if (_user) {
        _this.currentUser = JSON.parse(_user)
      } else {
        Toast('未注册')
        return
      }
      if(!_this.currentUser.authorizationCode){
        Toast('未授权')
        return
      }
      if(_this.currentUser.times <= 0){
        Toast('抱歉，您的次数已用完')
        return
      }
      // let audio = _this.$refs.shakeAudio
      // audio.pause()
      _this.startDisabled = true
      let param = {
        authorizationCode: _this.currentUser.authorizationCode
      }
      bobingService.startBobing(param).then(response => {
        let canBobing = response.canBobing
        if (canBobing == 0) {
          Toast('授权码无效')
        } else if (canBobing == 2) {
          Toast('活动未开始')
        } else if (canBobing == 3) {
          Toast('活动已结束')
        } else if (canBobing == 4) {
          Toast('抱歉，您的次数已用完')
        } else if (canBobing == 5) {
          Toast('未授权')
        } else if (canBobing == 10) {
          Toast('系统内部错误')
        } else if (canBobing == 11) {
          Toast('奖项配置错误')
        } else if (canBobing == 1){
          let points = response.points
          _this.rptIsShow = false
          let audio = _this.$refs.shakeAudio
          if (audio.paused) {
            audio.play()
          }
          _this.startBobingAnimation(response)
        }else{
          Toast('真奇怪了')
        }
        setTimeout(() => {
          _this.startDisabled = false
        }, 1500);
      }, error => {
        Toast('服务器内部错误:' + error)
        _this.startDisabled = false
      })
    
    },
    //开始动画
    startBobingAnimation(response) {
      let _this = this
      _this.ranRptList = response.points
      let code = response.canBobing
      let prizeType = response.prizeType
      let audio = _this.$refs.shakeAudio
      let vdo = _this.$refs.shakeAudioEnd
      if(prizeType == 0){
        vdo.src = _this.mzUrl
      }else if(prizeType == 1){
        vdo.src=_this.yxUrl;
      }else if(prizeType == 2){
        vdo.src = _this.ejUrl
      }else if(prizeType == 3){
        vdo.src = _this.sjUrl
      }else if(prizeType == 4){
        vdo.src = _this.shUrl
      }else if(prizeType == 5){
        vdo.src = _this.dtUrl
      }else if(prizeType >= 6){
        vdo.src = _this.zyUrl
      }
      audio.play()
      setTimeout(() => {
        vdo.play()
      }, 1500);
      setTimeout(() => {
        _this.rptIsShow = true
      }, 0);
      setTimeout(() => {
        _this.currentUser.times = response.times
        setUser(_this.currentUser)
        if (prizeType == 0) {
          console.log(vdo)
          //vdo.src=_this.yxUrl;
          Dialog.alert({
            title: '啥都没有',
            message: response.message,
            theme: 'round-button',
          }).then(() => {
            // on close
          });
        } else{
          let title = '恭喜您'
          let message = response.message
          Dialog.alert({
            title: title,
            message: message,
            theme: 'round-button',
          }).then(() => {
            // on close
          });
        }
      }, 2000);
    },
    statisticalFieldNumber(arr) {
      return arr.reduce(function (prev, next) {
        prev[next] = (prev[next] + 1) || 1;
        return prev;
      }, {});
    },
    getRptType(type) {
      let rlist = [] //点数列表
      let ranRpt //随机点数
      let ranCount = 6 //骰子数量
      for (let i = 0; i < ranCount; i++) {
        ranRpt = Math.floor(Math.random() * 6) + 1
        rlist.push(ranRpt)
      }
      return rlist;
    },
    clickLamp() {
      try {
        let myAudio = this.$refs.myaudio
        if (myAudio != null) {
          const device_type = navigator.userAgent
          const md = new MobileDetect(device_type);
          const system = md.os()
          if (system == 'iOS') {
            myAudio.playMusic()
          }
          this.showPopup = false
        }
      }
      catch (e) {
        Toast(e)
      }
    },
    closePopup() {

    },
    //注册
    regist() {
      this.rptIsShow = false
      this.$router.push({ path: '/register' })
    },
    //规则
    ruleClick() {
      this.rptIsShow = false
      this.$router.push({ path: '/rule' })
    },
    //我的
    myClick(){
      this.rptIsShow = false
      this.$router.push({ path: '/my' })
    },
    rankClick(){
      this.rptIsShow = false
      this.$router.push({ path: '/ranking' })
    },
    selectStart() {
      let that = this
      if (that.clickimes == 0) {
        setTimeout(
          function () {
            //2秒钟内点击超过6次，触发选择开始框
            if (that.clickimes >= 6) {
              that.showPassword = true
            }
            that.clickimes = 0
          }
          , 2000)
      }
      that.clickimes++
    },
    //开始活动
    commitStart(selectTag) {
      let _this = this
      if (_this.password == '0599024') {
        let tagName = ''
        if (selectTag == 0) {
          tagName = '重置'
        } else if (selectTag == 1) {
          tagName = '开始'
        }
        _this.$dialog.confirm({
          title: '提示',
          message: `确定${tagName}活动吗?`,
        })
          .then(() => {
            let param = {
              startTag: selectTag
            }
            console.log(param)
            bobingService.startactive(param).then(response => {
              Toast(`${tagName}活动成功`)
            }, error => {
              Toast(`${tagName}活动错误`)
            })
          })
          .catch(() => {
            // on cancel
          });
      }
      else {
        Toast('密码错误')
      }
    }
  },
  mounted() {
    let _this = this
    let _user = getUser()
    if(_user == 'null'){
      setUser(_this.currentUser)
      return
    }
    if (_user) {
      _this.currentUser = JSON.parse(_user)
      if(_this.currentUser.userName){
        _this.lampUserName = _this.currentUser.userName
      }
    }else{
      _this.currentUser.times = 0
    }
    console.log(_this.currentUser)
  },
  created() {
  },
  destroyed: function () {
    console.log('destroyed')
  },
  watch: {
    '$route.path': function (newVal, oldVal) {
      if (oldVal === '/register') {
        let _this = this
        let user = getUser()
        if (user) {
          _this.currentUser = JSON.parse(user)
        }
      }
    }
  },
  //取消页面缓存
  // beforeRouteLeave(to, from, next) {
  //     from.meta.keepAlive = false
  //     next()
  //   }
}